import symbol from 'log-symbols';
import chalk from 'chalk';
import ora from 'ora';
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const spawn = util.promisify(require("child_process").spawn);
const path = require('path');

import {
    notExistFold,
    prompt,
    downloadTemplate,
    updateJsonFile,
    addSites
} from './util';
import fs from "fs";
import inquirer from "inquirer";

let create = async() => {

    const { ProjectName } = await new Promise(resolve => {
        inquirer
            .prompt({
                type: 'input',
                name: 'ProjectName',
                message: '输入该项目名称'
            })
            .then(answer => {
                resolve(answer);
            })
    });

    // 项目名不能为空
    if (ProjectName === undefined) {
        console.log(symbol.error, chalk.greenBright('创建项目的时候，请输入项目名'));
    } else {
        // 如果文件名不存在则继续执行,否则退出
        notExistFold(ProjectName).then(() => {

            // 用户询问交互
            prompt().then((answer) => {

                /**
                 * 根据用户输入的配置信息下载模版&更新模版配置
                 * 下载模版比较耗时,这里通过ora插入下载loading, 提示用户正在下载模版
                 */
                let loading = ora('模板下载中...');
                loading.start('模板下载中...');

                let Api = '';
                switch (answer.frame) {
                    case 'single':
                        Api = 'direct:https://gitee.com/missshen/model';
                        break;
                    case 'sites':
                        Api = 'direct:https://gitee.com/missshen/model';
                        break;
                    default:
                        break;
                }

                downloadTemplate(ProjectName, Api)
                    .then(() => {

                        loading.succeed('模板下载完成');

                        // 下载完成后,根据用户输入更新配置文件
                        const fileName = `${ProjectName}/package.json`;
                        answer.name = ProjectName;
                        updateJsonFile(fileName, answer)
                            .then(async() => {
                                console.log(symbol.success, chalk.green('配置文件更新完成'));

                                if (answer.frame === 'sites') {
                                    const siteName = 'test';

                                    fs.mkdirSync(path.resolve(`${ProjectName}/sites`));

                                    addSites(siteName, `${ProjectName}/`)

                                    console.log(symbol.success, chalk.green('站点创建完成'));

                                    await loadCmd(`rm -rf *`, '删除单站点文件', ProjectName + '/src/pug')
                                }

                                await loadCmd(`cnpm install`, '安装依赖', ProjectName)

                                loadCmd(`beon d`, '运行项目', ProjectName, true)
                                console.log(symbol.success, chalk.green('已新开窗口进行运行，如长时间运行不动请按一下回车'));
                                process.exit(1);
                            })
                    }, () => {
                        loading.fail('模板下载失败');
                    });
            })
        });
    }
};

let loadCmd = async(cmd, text, cd, check) => {
    let loading = ora();
    const runner = check ? spawn : exec;
    loading.start(`${text}: 命令执行中...`);
    if (cd) {
        await runner(cmd, { cwd: path.resolve(process.cwd(), cd), detached: true, shell: true });
    } else {
        await runner(cmd);
    }
    loading.succeed(`${text}: 命令执行完成`);
}

module.exports = create;
